// 发送验证码



const nodemailer = require('nodemailer');
const smtpTransport = require('nodemailer-smtp-transport');
import Email_code from "../../models/email_code.js";
import is_test from '../../util/test'
import Jwt from "../../prototype/jwt";


class V1 extends Jwt {
  constructor() {
    super();
    //密钥，当然实际的项目中密钥应该变态一些
    this.optionsEmailConfig163 = {
      host: "smtp.163.com", // 网易的邮件地址
      port: 994, // 端口
      secureConnection: false, // use SSL
      secure: true,
      auth: {
        "user": 'sym15201259544@163.com', // 邮箱账号
        "pass": 'NFNSAKDLUHNQKARS' // 邮箱的授权码
      }
    }
  }


  email_html(context = {}) {
    return `
<!DOCTYPE html>
<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>${context.title || '获取验证码'}</title>
    <meta charset="utf-8" />
  </head>
    <body>
      <div class="code-box" style="
          padding: 30px;
          background: #e4e4e4;
          margin: 30px auto;
          width: 90%;

          box-sizing: border-box ">
          <h1 class="code-title"
              style="
              padding: 10px;
              border-bottom: 1px solid #dadada;
              font-size: 16px;color: #333;">
              ${context.desc || '感谢你的使用本站观看~'}
          </h1>
          <p class="text1" style="
          font-size: 18px;
          color:#000;">
              你好，你本次验证码为：
               <u style="font-size: 28px;color:#1890ff;display: block; padding: 20px 0;font-weight: bold">${context.code}</u>
          </p>
          <p class="text2" style="  font-size: 14px;color:#666;">
              本次验证码有效期为10分钟，请尽快回到页面输入验证码，完成操作<br>
              <u>http://120.55.70.227:9004/</u>
          </p>
          <p class="code-bottom-text" style="border-top: 1px solid;#dadada; font-size: 12px; color: #666">
              如果你已经完成了操作，请忽略此邮箱。
         </p>
      </div>
  </body>
</html>
`
  }

  /**
   * 发送验证码 type 1 注册 2 忘记密码 ..
   * @param context [email， type， title, desc, ]
   * @returns {Promise<{msg: string, email_code: *, status: number}>}
   */
  async email({type, title, desc, email}) {
    const context = {};
    const body = {
      msg: '发送成功',
      status: 200,
      email_code: {},
    };
    context.type = type || 1;
    context.title = title || '获取验证码';
    context.desc = desc || '感谢你使用本站观看视频';
    context.code = '0000';
    try {
      if (!is_test.email(email)) {
        throw new Error('邮箱格式错误!')
      }
      if (!['1', '2'].includes(type)) {
        throw new Error('参数无效!')
      }

      const transporter = nodemailer.createTransport(smtpTransport(this.optionsEmailConfig163));
      await Email_code.deleteMany({email, type: context.type})
      const email_code = await Email_code.create({email, type: context.type})
      context.code = email_code.code;
      body.email_code = email_code;
      const thisName = `admin<${this.optionsEmailConfig163.auth.user}>`
      const mailOptions = {
        from: thisName, // 发件人地址
        to: [thisName, 'username<' + email + '>'], // 收件人地址，多个收件人可以使用逗号分隔
        subject: context.title, // 邮件标题
        html: this.email_html(context) // 邮件内容
      };

      await transporter.sendMail(mailOptions, async function (error, info) {
        if (error) {
          await Email_code.deleteMany({email, type: context.type})
          console.log('error', error);
          transporter.close(); // 如果没用，关闭连接池
          throw new Error('找不到邮箱或拒绝访问!')
        }
        // console.log(info)
        transporter.close(); // 如果没用，关闭连接池
      });

    } catch (e) {
      body.status = 201
      body.msg = e.toString() || '发送失败'
    }

    return body;
  }


  async is_email_code({type, email, code}) {
    const body = {
      msg: '验证有效',
      status: 200,
      email_code: {},
    };

    try {
      if (!['1', '2'].includes(type)) {
        throw new Error('参数无效')
      }

      if (!is_test.email(email)) {
        throw new Error('邮箱格式错误')
      }

      body.email_code = await Email_code.findOne({$and: [{email: email},{ type: type}]});
      if (!body.email_code) {
        throw new Error('验证码无效')
      } else {
        let start = 1000 * 60 * 60 * 24;
        // let start = 1000 * 60;// 一分钟过期
        let end = new Date().getTime() - new Date(body.email_code.create_date).getTime();
        if (code * 1 !== body.email_code.code || end > start) {
          throw new Error('验证码已失效')
        }
        await Email_code.deleteMany({email: email, type: type});
      }
    } catch (e) {
      body.msg = e.toString() || '验证码无效'
      body.status = 201;
    }

    return body;
  }

}

export default V1;

